package com.woniuxy.controllers;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.woniuxy.entitys.TbCustomer;
import com.woniuxy.services.CustomerService;
import com.woniuxy.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@RestController
public class CustomerController {

    @Autowired
    private CustomerService customerService;
    @Autowired
    private JWTUtils jwtUtils;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/customer/list")
    public ResultVO getCustomerList(@RequestBody Map<String,Object> map){
        Integer pageNum = (Integer) map.get("pageNum");
        Integer pageSize = (Integer) map.get("pageSize");
        PageInfo<TbCustomer> pageInfo = customerService.getAllCustomers(pageNum,pageSize);
        return pageInfo!=null?ResultVO.success("success",pageInfo):ResultVO.failure("failed");
    }

    @PostMapping("/customer/tel")
    public ResultVO getCustomerByTel(@RequestBody Map<String,Object> map){
        Integer pageNum = (Integer) map.get("pageNum");
        Integer pageSize = (Integer) map.get("pageSize");
        String telphoneCondition = (String) map.get("telphoneCondition");
        PageInfo<TbCustomer> pageInfo = customerService.getOneByTel(pageNum,pageSize,telphoneCondition);
        return pageInfo!=null?ResultVO.success("success",pageInfo):ResultVO.failure("failed");
    }

    @PostMapping("/customer/condition")
    public ResultVO getCustomersByCondition(@RequestBody Map<String,Object> map){
        Integer pageNum = (Integer) map.get("pageNum");
        Integer pageSize = (Integer) map.get("pageSize");
        Integer radio = (Integer) map.get("radio");
        String beginTimeStr = (String) map.get("beginTime");
        String endTimeStr = (String) map.get("endTime");
        Date beginTime = new Date();
        Date endTime = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(beginTimeStr!="" && beginTimeStr!=null){
            try {
                beginTime = simpleDateFormat.parse(beginTimeStr);
                endTime = simpleDateFormat.parse(endTimeStr);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            PageInfo<TbCustomer> pageInfo = customerService.getByCondition(pageNum,pageSize,beginTime,endTime,radio);
            return pageInfo!=null?ResultVO.success("success",pageInfo):ResultVO.failure("failed");
        }
        PageInfo<TbCustomer> pageInfo =customerService.getByRadio(pageNum,pageSize,radio);
        return pageInfo!=null?ResultVO.success("success",pageInfo):ResultVO.failure("failed");
    }

    /*
     查询客户详细信息
     */
    @GetMapping("/customer/detail/{cid}")
    public ResultVO getCustomerDetailByCid(@PathVariable("cid") Integer cid){
        TbCustomer tbCustomer = customerService.getDetailByCid(cid);
        return tbCustomer!=null?ResultVO.success("success",tbCustomer):ResultVO.failure("failed");
    }

    /**
     * 查询客户个人信息
     * @return
     */
    @PostMapping("/customer/getCustomerInfo/{phone}")
    public ResultVO getCustomerInfo(@PathVariable String phone){
        TbCustomer customer = customerService.getCustomerInfo(phone);
        if(customer == null) {
            return ResultVO.failure("没有数据");
        } else {
            return ResultVO.success("查询成功", customer);
        }
    }

    /**
     * 修改客户个人信息
     * @return
     */
    @PostMapping("/customer/modifyInfo")
    public ResultVO modifyInfo(@RequestBody TbCustomer tbCustomer){
        if(customerService.modifyInfo(tbCustomer)) {
            return ResultVO.success("修改成功");
        } else {
            return ResultVO.failure("修改失败");
        }
    }


    /**
     * 导出数据
     * @param response
     * @throws IOException
     */
    @PostMapping("/customer/export")
    public void export(HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
            System.out.println(fileName);
            response.setHeader("Content-disposition", "attachment;filename=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), TbCustomer.class).autoCloseStream(Boolean.FALSE).sheet("模板")
                    .doWrite(customerService.selectAll());//doWrite方法的参数是一个list，这里调用service层的代码获得一个list，这个list就是要导出的数据
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }
}
